<?php

namespace app\shop\controller;

use think\captcha\facade\Captcha;
use think\facade\Db;

class Login
{
    public function login()
    {
        $username = input('username');
        $password = input('password');
        $shop = Db::name('shop')->where(['link_phone' => $username])->find();
        if (!$shop || md5($shop['password']) != md5($password)) {
            return errorJson('账号或密码错误');
        }
        $token = uniqid() . $shop['id'];
        session_id($token);
        session_start();
        $_SESSION['shop'] = json_encode($shop);

        return successJson(['token' => $token], '登录成功');
    }

    public function reg()
    {
        $agent_id = input('agent_id', 0);
        $link_phone = input('link_phone', '', 'trim');
        $link_name = input('link_name', '', 'trim');
        $password = input('password', '', 'trim');
        $title = input('title', '', 'trim');
        $address = input('address', '', 'trim');

        if (!$agent_id) {
            return errorJson('只能通过邀请链接注册');
        }

        $agent = Db::name('agent')
            ->where([
                'id' => $agent_id
            ])
            ->find();
        if (!$agent) {
            return errorJson('邀请链接已失效，请重新获取');
        }

        if (!preg_match("/^1[3456789]\d{9}$/", $link_phone)) {
            return errorJson('请输入正确的手机号码');
        }
        if (strlen($password) < 6 || strlen($password) > 18) {
            return errorJson('密码长度不符合规范（需6-18位）');
        }

        // 验证店铺名字
        $shop = Db::name('shop')
            ->where([
                'title' => $title
            ])
            ->find();
        if ($shop) {
            return errorJson('此店铺名字已被占用，请更换');
        }

        // 验证手机号
        $shop = Db::name('shop')
            ->where([
                'link_phone' => $link_phone
            ])
            ->find();
        if ($shop) {
            return errorJson('此手机号已被占用，请更换');
        }
        $rs = Db::name('shop')
            ->insert([
                'agent_id' => $agent_id,
                'link_phone' => $link_phone,
                'link_name' => $link_name,
                'title' => $title,
                'password' => $password,
                'address' => $address,
                'add_time' => time()
            ]);
        if ($rs !== false) {
            return successJson('', '注册成功');
        } else {
            return errorJson('注册失败，请重试');
        }
    }

    /**
     * 验证码
     */
    public function verify()
    {
        return Captcha::create();
    }
}
